import React, { PureComponent } from 'react';
import {
  Select,
  Icon,
  message,
  Form,
  Input,
  InputNumber,
  Tooltip,
  Radio,
  Card,
} from 'antd';

import { LZFormItem } from '@/components/LZForm';
const FormItem = Form.Item;
const dayMap = [1, 3, 7, 30, 90, 180, 365, 730];
const largeFormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

@Form.create()
class NewProductSku extends PureComponent {
  state = {
    uploading: false,
    marketPrice: 0,
    salePrice: '',
    minIndex: 0,
    maxIndex: 0,
    minDays: 0,
    maxDays: 0,
    validateStatus: '',
    minHelp: '',
    maxHelp: ''
  };

  componentDidMount() {
    const { productSkuses } = this.props;
    const { cycs = [], marketPrice } = productSkuses;
    if (cycs.length === 1) {
      const days = cycs[0].days;
      const dayIndex = dayMap.findIndex(f => f === days);
      this.setState({
        minDays: days,
        maxDays: days,
        minIndex: dayIndex,
        maxIndex: dayIndex,
        marketPrice,
      });
    } else {
      let _cycs = cycs.sort((a, b) => Number(a.days) - Number(b.days));
      this.setState({
        minDays: _cycs[0].days,
        marketPrice,
        maxDays: _cycs[_cycs.length - 1].days,
        minIndex: dayMap.findIndex(f => f === _cycs[0].days),
        maxIndex: dayMap.findIndex(f => f === _cycs[_cycs.length - 1].days),
      });
    }
  }

  // 改变最小租期时的处理
  changeMin = evt => {
    const { maxIndex, marketPrice, maxDays } = this.state;
    const { productSkuses, changeSku, index } = this.props;
    const value = evt.target.value;
    if (value > maxDays) {
      this.setState({
        minHelp: '最短租期请小于等于最高租期',
        maxHelp: '',
        validateStatus: 'min'
      });
    } else {
      this.setState({
        minHelp: '',
        maxHelp: '',
        validateStatus: ''
      });
    }
    const dayIndex = dayMap.findIndex(f => f === value);
    if (maxIndex >= dayIndex) {
      const _productSkuses = { ...productSkuses };
      const diff = maxIndex - dayIndex;
      _productSkuses.cycs = [];
      for (let i = 0; i < diff + 1; i++) {
        _productSkuses.cycs.push({
          days: dayMap[maxIndex - i],
          price: '',
          salePrice: '',
        });
      }
      _productSkuses.cycs = _productSkuses.cycs.sort((a, b) => Number(a.days) - Number(b.days));
      _productSkuses.cycs = _productSkuses.cycs.map((v, index) => {
        if (v.days <= 180) {
          v['salePrice'] = (marketPrice * 1.24).toFixed(4);
        } else if (v.days >= 365) {
          v['salePrice'] = (marketPrice * 1.35).toFixed(4);
        }
        return v;
      });
      changeSku(_productSkuses, index);
    }
    this.setState({
      minDays: value,
      minIndex: dayIndex,
    });
  };

  // 改变最大租期时的处理
  changeMax = evt => {
    const value = evt.target.value;
    const { minIndex, marketPrice, minDays } = this.state;
    const { productSkuses, changeSku, index } = this.props;
    const dayIndex = dayMap.findIndex(f => f === value);
    if (value < minDays) {
      this.setState({
        maxHelp: '最高租期请大于等于最短租期',
        minHelp: '',
        validateStatus: 'max'
      });
    } else {
      this.setState({
        minHelp: '',
        maxHelp: '',
        validateStatus: ''
      });
    }
    if (minIndex <= dayIndex) {
      const _productSkuses = { ...productSkuses };
      const diff = dayIndex - minIndex;
      _productSkuses.cycs = [];
      for (let i = 0; i < diff + 1; i++) {
        _productSkuses.cycs.push({
          days: dayMap[minIndex + i],
          price: '',
          salePrice: '',
        });
      }
      _productSkuses.cycs = _productSkuses.cycs.sort((a, b) => Number(a.days) - Number(b.days));
      _productSkuses.cycs = _productSkuses.cycs.map((v, index) => {
        if (v.days <= 180) {
          v['salePrice'] = (marketPrice * 1.24).toFixed(4);
        } else if (v.days >= 365) {
          v['salePrice'] = (marketPrice * 1.35).toFixed(4);
        }
        return v;
      });
      changeSku(_productSkuses, index);
    }
    this.setState({
      maxDays: value,
      maxIndex: dayIndex,
    });
  };

  changeCycsPrice = (evt, inputIndex, field) => {
    console.log(evt);
    const value = evt;
    const { productSkuses, changeSku, index } = this.props;
    const { minIndex } = this.state;
    const _productSkuses = { ...productSkuses };
    const { cycs = [] } = _productSkuses;
    cycs[inputIndex - minIndex][field] = value;
    changeSku(_productSkuses, index);
  };

  changeSkuField = (evt = 0, field) => {
    let value = evt;
    // if (field === 'inventory') {
    //   // 库存向下取整
    //   value = evt && Math.floor(evt);
    //   console.log(value);
    //   document.querySelector('#inventory').value = value;
    // }
    const { productSkuses, changeSku, index } = this.props;
    let _productSkuses = { ...productSkuses };
    if (field === 'marketPrice') {
      _productSkuses.cycs = _productSkuses.cycs.map((v, index) => {
        if (v.days <= 180) {
          v['salePrice'] = (value * 1.24).toFixed(4);
        } else if (v.days >= 365) {
          v['salePrice'] = (value * 1.35).toFixed(4);
        }
        return v;
      });
      this.setState({
        marketPrice: value,
      });
    }
    _productSkuses[field] = value;
    changeSku(_productSkuses, index);
  };

  renderError = (day, dayIndex) => {
    const { minIndex } = this.state;
    const { productSkuses } = this.props;
    const { cycs = [], marketPrice } = productSkuses;
    const salePrice = cycs[dayIndex - minIndex].salePrice || 0;
    let isError = false;
    if (day >= 365) {
      isError = salePrice > (Number(marketPrice) * 1.35).toFixed(4);
    } else if (day <= 180) {
      isError = salePrice > (Number(marketPrice) * 1.24).toFixed(4);
    }
    if (isError) {
      return <div className="red error-sale">销售价已超出平台规定</div>;
    }
  };

  render() {
    const {
      index,
      form: { getFieldDecorator },
      productSkuses = {},
      specs = [],
      deleteSku,
      isBuyout,
    } = this.props;
    const { cycs = [], oldNewDegree, inventory, marketPrice, specAll } = productSkuses;
    const { minIndex, maxIndex, minDays, maxDays, validateStatus, minHelp, maxHelp } = this.state;

    const checkMaxRent = (_, value, callback) => {
      console.log(maxDays, minDays);
      if (!value) {
        callback('请设置最高租期');
        return;
      }

      if (value && minDays && value < minDays) {
        callback(`最高租期请大于等于最短租期`);
        return;
      }
      callback();
    };
    const checkMinRent = (_, value, callback) => {
      if (!value) {
        callback('请设置最短租期');
        return;
      }
      if (value && maxDays && value > maxDays) {
        callback(`最短租期请小于等于最高租期`);
        return;
      }
      callback();
    };

    const close = (colorTitle, specTitle) => {
      deleteSku(index, colorTitle, specTitle);
    };

    const label = (
      <label className="">
        销售价格
        <Tooltip
          title="商家须认真设置销售价格，租户在租期中，到期买断价格=销售价格-累计支付的租金
        中途买断价=官方售价+（总租金+到期买断价-官方售价）*实际租用天数/总租用天数-已付租金
        当租期>=360天时，销售价需<=官方售价*1.35；当租期<=180天时，销售价需<=官方售价*1.24；"
        >
          <Icon type="info-circle" />
        </Tooltip>
      </label>
    );

    let title = '';
    let colorTitle = '',
      specTitle = '';
    if (specs.values.length) {
      colorTitle = specAll[0].platformSpecValue || '';
      specTitle = specAll[1].platformSpecValue || '';
    }
    title = colorTitle ? colorTitle + '/' + specTitle : specTitle;

    return (
      <Card
        title={title}
        style={{ marginBottom: '10px' }}
        extra={<Icon type="close" onClick={evt => close(colorTitle, specTitle)} />}
      >
        <Form>
          <LZFormItem
            formItemLayout={largeFormItemLayout}
            label="官方售价"
            field="marketPrice"
            requiredMessage="请输入官方售价"
            getFieldDecorator={getFieldDecorator}
            onChange={evt => this.changeSkuField(evt, 'marketPrice')}
            initialValue={marketPrice}
          >
            <InputNumber placeholder="元" />
          </LZFormItem>
          <LZFormItem
            formItemLayout={largeFormItemLayout}
            label="库存数量"
            field="inventory"
            requiredMessage="请输入库存数量"
            getFieldDecorator={getFieldDecorator}
            onChange={evt => this.changeSkuField(evt, 'inventory')}
            initialValue={inventory}
          >
            <InputNumber placeholder="数量" step="1" formatter={value => Math.floor(value) || ''}
                         parser={value => Math.floor(value) || ''} type="number" />
          </LZFormItem>
          <LZFormItem
            formItemLayout={largeFormItemLayout}
            className="rent-row"
            label="最短租期"
            field="minDays"
            requiredMessage="请选择最短租期"
            getFieldDecorator={getFieldDecorator}
            initialValue={minDays}
            validateStatus={validateStatus === 'min' ? 'error': ''}
            help={minHelp}
            // rules={[{ validator: checkMinRent }, { validator: checkMaxRent }, ]}
          >
            <Radio.Group onChange={this.changeMin} className="sku-radio">
              {dayMap.map(day => {
                return (
                  <Radio value={day} key={day}>
                    {day}天
                  </Radio>
                );
              })}
            </Radio.Group>
          </LZFormItem>
          <LZFormItem
            className="rent-row"
            formItemLayout={largeFormItemLayout}
            label="最高租期"
            field="maxDays"
            getFieldDecorator={getFieldDecorator}
            initialValue={maxDays}
            validateStatus={validateStatus === 'max'? 'error': ''}
            help={maxHelp}
            // rules={[{ validator: checkMaxRent }, { validator: checkMinRent }, ]}
          >
            <Radio.Group onChange={this.changeMax} className="sku-radio">
              {dayMap.map(day => {
                return (
                  <Radio value={day} key={day}>
                    {day}天
                  </Radio>
                );
              })}
            </Radio.Group>
          </LZFormItem>
          <LZFormItem
            formItemLayout={largeFormItemLayout}
            label="租期"
            field="oldNewDegree"
            getFieldDecorator={getFieldDecorator}
            initialValue={oldNewDegree}
          >
            <div className="df">
              {dayMap.map(day => {
                return (
                  <div
                    className={`${
                      day >= minDays && day <= maxDays ? '' : 'disabled'
                    } w70 day-item mr-20 ml-20`}
                  >
                    {day}天
                  </div>
                );
              })}
            </div>
          </LZFormItem>
          <FormItem {...largeFormItemLayout} label="租赁平均价" required>
            <div className="df">
              {dayMap.map((day, index) => {
                // 判断租赁平均价的规则
                const price =
                  index < minIndex || index > maxIndex || !cycs[index - minIndex]
                    ? undefined
                    : cycs[index - minIndex].price;
                const disabled =
                  minDays > maxDays ||
                  index < minIndex ||
                  (index > maxIndex && !cycs[index - minIndex]);
                return (
                  <div className="ml-13">
                    <InputNumber
                      disabled={disabled}
                      placeholder="元/天"
                      onChange={evt => this.changeCycsPrice(evt, index, 'price')}
                      value={price}
                      className="w70"
                    />
                    {price || disabled ? (
                      ''
                    ) : (
                      <div className="red error-sale">请输入租赁平均价</div>
                    )}
                  </div>
                );
              })}
            </div>
          </FormItem>
          {isBuyout ? (
            <FormItem {...largeFormItemLayout} label={label} required>
              <div className="df">
                {dayMap.map((day, index) => {
                  const salePrice =
                    index < minIndex || index > maxIndex || !cycs[index - minIndex]
                      ? undefined
                      : cycs[index - minIndex].salePrice;
                  const disabled =
                    minDays > maxDays ||
                    index < minIndex ||
                    (index > maxIndex && !cycs[index - minIndex]);
                  const canRenderError = !(
                    index < minIndex ||
                    index > maxIndex ||
                    !cycs[index - minIndex]
                  );
                  return (
                    <div className="ml-13">
                      <InputNumber
                        placeholder="元"
                        className="w70"
                        onChange={evt => this.changeCycsPrice(evt, index, 'salePrice')}
                        value={salePrice}
                        disabled={disabled}
                      />
                      {canRenderError && this.renderError(day, index)}
                      {salePrice || disabled ? (
                        ''
                      ) : (
                        <div className="red error-sale">请输入销售价格</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </FormItem>
          ) : null}
        </Form>
      </Card>
    );
  }
}
export default NewProductSku;
